<template>
  <div>
    <div style="width: 40%;margin-bottom: 12px" class="flex-row">
      <input ref="ipt" class="ipt" v-model="queryGoods.keyword" />
      <el-button type="primary" @click="queryGoods01">搜索</el-button>
    </div>
    <vue-context-menu
      :context-menu-data="contextMenuData"
      @tableConfig="tableConfig"
      @deletedata="deletedata"
      @removeStorage="removeStorage"
    />

    <!-- 表格配置 -->
    <el-dialog
      title="表格配置"
      :visible.sync="tableConfigShow01"
      append-to-body
      width="100%"
    >
      <j-table-column-config :columns.sync="header" @tabSave="tabSave" @pit="pit" />
    </el-dialog>
    <div class="tabBox">
      <el-table
        v-if="isShowTable"
        ref="table"
        height="555"
        :data="goodsList"
        border
        highlight-current-row="highlight-current-row"
        @row-dblclick="setGoods"
        current-change="currentChange"
        style="width: 100%"
        @header-dragend="changeColWidth"
        @contextmenu.native="showMenu"
        @sort-change="sortTab"
      >
        <el-table-column
          v-for="(item, index) in header"
          v-if="item.visible"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp="item.prop"
          :sortable="item.sortable?'custom':false"
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <span v-if="item.type == 1" style="margin-left: 10px">{{ scope.row[`${item.prop}`] }}</span>
            <span v-else-if="item.type == 2" style="margin-left: 10px">{{ parseTime(scope.row[`${item.prop}`]) }}</span>
            <span v-else-if="item.type == 3" style="margin-left: 10px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
            <span v-else-if="item.type == 4" style="margin-left: 10px">
              <span v-if="item.prop === 'usableNum'" :ref="'ref'+scope.$index">
                {{ computedNum(scope.row) }}
              </span>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex flex-row">
        <div style="width: 70%">
          <el-pagination
            :current-page.sync="query.page"
            :page-sizes="[10,20,50, 100]"
            :page-size="query.size"
            layout="sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <div class="bottomBtn">
          <el-button type="primary" class="btn_1" @click="closeDialog">取消</el-button>
          <el-button type="primary" class="btn_1" @click="pushGoods">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { getGoods } from '@/api/erp/basGoods'
import { queryGoods } from '@/utils/key'

import { tablemixins } from '@/mixins/tablemixins'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import Sortable from 'sortablejs'

export default {
  name: 'JGoodsSelect',
  components: { jTableColumnConfig },
  mixins: [queryGoods, tablemixins],
  props: {
    queryGoods: {
      type: Object,
      default: null
    },
    showQueryGoods: {
      type: Boolean,
      default: false
    },
    type: {
      type: String
    },
    customerId: {
      type: [String, Number]
    },
    buyChannel: {
      type: [String, Number],
      default: ''
    },
    noReturnBox: {
      type: Boolean,
      default: true
    },
    tableName: {
      type: String,
      default: 'table'
    }
  },
  data() {
    return {
      query: {
        page: 1,
        size: 20,
        sort: 'goodsCode,asc'
      },
      ignoreGoodsTagNames: '',
      tableConfigShow01: false,
      goodsList: [],
      total: 0,
      header: [
        {
          'dictionary': '',
          'label': '商品编码',
          'prop': 'goodsCode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '商品名称',
          'prop': 'goodsName',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 500
        },
        {
          'dictionary': '',
          'label': '条形码',
          'prop': 'barcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        }, {
          'dictionary': '',
          'label': '可用量',
          'prop': 'usableNum',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        },
        {
          'dictionary': '',
          'label': '可用辅数量',
          'prop': 'usableNum',
          'showName': '',
          'type': '4',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '单价',
          'prop': 'taxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        },
        {
          'dictionary': '',
          'label': '箱价',
          'prop': 'taxBoxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        }
      ],
      contextMenuData: {
        menuName: 'table1',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [{
          fnHandler: 'tableConfig', // 绑定事件
          icoName: 'el-icon-setting', // icon图标
          btnName: '表格设置' // 菜单名称
        }, {
          fnHandler: 'removeStorage', // 绑定事件
          icoName: 'el-icon-delete', // icon图标
          btnName: '清除缓存' // 菜单名称
        }
        ]
      }
    }
  },
  activated() {
    this.onGet()
  },
  created() {
    const header = JSON.parse(localStorage.getItem('jGoodsSelect'))
    this.header = header || this.header
    if (this.noReturnBox) {
      this.queryGoods.ignoreGoodsTagNames = '回瓶回箱,瓶盖'
    }else {
      this.queryGoods.ignoreGoodsTagNames = ''
    }

    this.onGet()
  },
  mounted() {
    // this.$refs.ipt.focus()
  },
  methods: {
    queryInit() {
      this.query.page = 1
      this.query.size = 50
      this.goodsList = []
    },
    queryGoods01() {
      this.query.page = 1
      this.onGet()
    },
    onGet() {
      getGoods({ ...this.query, ...this.queryGoods, type: this.type, customerId: this.customerId, buyChannel: this.buyChannel }).then(res => {
        this.goodsList = res.content
        this.total = res.totalElements
        this.$refs.table.setCurrentRow(this.goodsList[0])
      })
    },
    computedNum(goods) {
      const boxCount = parseInt(goods.usableNum / Number(goods.boxUnitCount))
      const mainCount = goods.usableNum % Number(goods.boxUnitCount)
      return `${boxCount}${goods.boxUnitName}${mainCount}${goods.mainUnitName}`
    },
    pushGoods() {
      this.$emit('diaLogGoodsChange', { data: this.$refs.table.store.states.currentRow, row: this.$parent.$parent.$refs[this.tableName].store.states.currentRow, index: this.queryGoods.index })
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.onGet()
    },
    handleSizeChange(val) {
      this.query.size = val
      this.onGet()
    },
    closeDialog() {
      this.$emit('closeDialog', '1')
    },
    setGoods(val){
      this.pushGoods()
    },
    showMenu() {
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
    },
    tableConfig() {
      this.tableConfigShow01 = true
    },
    deletedata() {
    },
    toUpdateHeader() {
      console.log(this.header)
      localStorage.setItem('jGoodsSelect', JSON.stringify(this.header))
    },
    pit() {
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    initSortable() {
      const th = this
      const el = document.querySelector('.tabBox .el-table__header-wrapper thead tr')
      // 创建拖拽对象
      new Sortable(el, {
        onEnd(evt) {
          const { newIndex, oldIndex, item } = evt
          // 获取原来title的name
          const oldtitle = item.children[0].innerHTML
          let thOldIndex = -1
          // 根据name获取所在的索引
          for (let i = 0; i < th.header.length; i++) {
            if (th.header[i].showName === oldtitle) {
              thOldIndex = i
              break
            }
          }
          // 获取隐藏后的数组
          const list = th.header.filter(item => item.visible === true)
          // 获取新位置所在的name值
          const newtitle = list[newIndex].showName
          // 根据name获取所在的索引
          let thNewIndex = -1
          for (let i = 0; i < th.header.length; i++) {
            if (th.header[i].showName === newtitle) {
              thNewIndex = i
              break
            }
          }

          const temp = th.header[thOldIndex]
          if (temp === null || temp === undefined) {
            return
          }
          th.header.splice(thOldIndex, 1)
          th.header.splice(thNewIndex, 0, temp)
          th.toUpdateHeader()
          th.handleCancelSort()
        }
      })
    },
    handleCancelSort() {
      // 使table先隐藏，再显示，table将恢复拖拽之前的样式
      this.isShowTable = false
      setTimeout(() => {
        this.isShowTable = true
        // 必须延时，否则重新初始化的sortable无法拖拽
        setTimeout(() => {
          this.initSortable()
        }, 500)
      }, 100)
    },
    getDict(str) {
      return eval(str)
    },
    removeStorage() {
      localStorage.removeItem('jGoodsSelect')
      this.header = [
        {
          'dictionary': '',
          'label': '商品编码',
          'prop': 'goodsCode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        },
        {
          'dictionary': '',
          'label': '商品名称',
          'prop': 'goodsName',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '条形码',
          'prop': 'barcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        }, {
          'dictionary': '',
          'label': '可用量',
          'prop': 'usableNum',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '可用辅数量',
          'prop': 'usableNum',
          'showName': '',
          'type': '4',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '单价',
          'prop': 'taxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '箱价',
          'prop': 'taxBoxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        }
      ]
    },
    changeColWidth(nw, ow, col, evt) {
      const list = this.header
      list.map((res, i) => {
        if (res.label.indexOf(col.label) !== -1) {
          this.header[i].width = nw
        }
      })
      this.toUpdateHeader()
    },
    columnLabel(obj) {
      if (obj.showName) {
        return obj.showName
      }
      obj.showName = obj.label
      return obj.showName
    },
    tabSave() {
      this.tableConfigShow01 = false
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    sortTab(row) {
      if (row.column.order) {
        this.query.sort = `${row.column.property},${row.column.order === 'ascending' ? 'asc' : 'desc'}`
      } else {
        try {
          this.query.sort = null
        } catch (e) {
          console.err(e)
        }
      }
      this.onGet()
    }
  }
}
</script>

<style lang="scss" scoped>
.flex-row{
  display: flex;
  flex-direction: row;
}
.bottomBtn{
  display: flex;
  flex-direction: row-reverse;
  width: 30%;
  .btn_1{
    margin: 10px;
  }
}
.ipt{
  width: 100%;
  border: rgba(200,200,200,0.8) solid 1px;
}
</style>
